from rest_framework import serializers
import re
from django_redis import get_redis_connection
from .models import User
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email
from .models import Address
from goods.models import SKU


class SKUSerializer(serializers.ModelSerializer):
    """用户浏览记录序列化器"""

    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']







class UserBrowsingHistorySerializer(serializers.Serializer):
    """
    用户浏览记录序列化器
    接受sku_id,校验sku_id,保存sku_id到redis
    """
    sku_id = serializers.IntegerField(label='商品ID', min_value=1)

    def validate_sku_id(self, value):
        """
        校验sku_id
        :param value:sku_id
        :return: sku_id
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')

        return value

    def create(self, validated_data):
        """
        重写create方法，将sku_id存储到redis
        :param validated_data: {'sku_id':1}
        :return: validated_data
        """
        sku_id = validated_data.get('sku_id')
        user_id = self.context['request'].user.id

        # 创建连接到redis对象
        redis_coon = get_redis_connection('history')
        # 创建管道
        pl = redis_coon.pipeline()

        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 添加
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行
        pl.execute()

        return validated_data











class UserAddressSerializer(serializers.ModelSerializer):
    """用户地址序列化器"""
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ['user', 'create_time', 'update_time', 'is_deleted']
        # exclude  排除字段

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """重写create方法，增加地址的外键存储"""
        # 读取当前经过认证权限的用户
        # user = validated_data['user']
        user = self.context['request'].user
        validated_data['user'] = user


        # address = Address.objects.create(**validated_data)
        # return address
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)








class EmailSerializer(serializers.ModelSerializer):
    """添加邮箱序列化器"""

    class Meta:
        model = User
        fields = ['id','email']

        extra_kwargs = {
            'email':{
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """重写该方法：
        我们只对email进行存储
        后续还会在这里发送邮件：需要在更新数据成功之后，返回响应之前发送邮件
        instance ： 表示当前登录用户对象
        """
        instance.email = validated_data['email']
        instance.save()   # save() 是ORM方法

        # 获取邮箱激活链接
        verify_url = instance.generate_email_verify_url()

        # 更新完邮箱之后，处理响应之前，异步发送邮箱验证的邮件
        send_verify_email.delay(instance.email, verify_url)

        return instance





class UserDetailSerializer(serializers.ModelSerializer):
    """对用户基本信息进行序列化"""

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']







class CreateUserSerialiter(serializers.ModelSerializer):
    # 定义模型外部字段
    password2 = serializers.CharField(label='确认密码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)

    # 增减token字段
    token = serializers.CharField(label='登陆状态Token', read_only=True)


    class Meta:
        model = User
        # 所有字段：'id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        # 模型内部字段：'id', 'username', 'mobile', 'password'
        # 模型以外字段：'password2', 'sms_code', 'allow'
        # 输入字段(write_only)：'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        # 输出字段(read_only)：'id', 'username', 'mobile'
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'token']

        # 给username  password 指定额外参数
        extra_kwargs = {
            'username':{
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名'
                }
            },
            'password':{
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }


    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match('1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_coon = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_coon.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data




    def create(self, validated_data):
        """
        重写序列化器create方法，因为有些字段默认不能给User里面存储
        :param validated_data: 经过校验之后的数据
        :return: user / 输出字段(read_only)：'id', 'username', 'mobile'
        """
        # 删除不需要保存到User里面的数据
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']
        # 自己实现保存数据到User
        user = User.objects.create(**validated_data)

        # 调用django的用户认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 必须在注册或者登录之后，响应注册或者登录结果之前，生成jwt_token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成载荷：包含了user_id,username,email
        payload = jwt_payload_handler(user)
        # jwt_token
        token = jwt_encode_handler(payload)

        # 将token添加到user : python是面向对象的高级动态编程语言
        user.token = token

        # 响应数据,只会响应read_only 字段
        # 输出字段(read_only)，‘id' 'username' 'mobile' 'token'
        return user
